import { Module, ActionContext } from 'vuex'
import { StateAppModule, RootStateTypes } from '../interface/index'
import { login, refreshLogin } from '@/api/login'
import { setSession, clearSession, getSession } from '@/utils/storage'
import router from '@/router'
import {
  ModuleState,
  ModuleGetters,
  ModuleActions,
  ModuleMutations
} from '../hooks';

const state: StateAppModule = {
  requestCount: {
    count: 0,
    time: 0
  }, // 过期请求次数
  token: '', // token
  refreshToken: '', // refreshToken
  userInfo: null, // 用户信息
  menuList: [], // 静态路由菜单栏 目前暂时未使用，用的是routeList中的routeList
}

const getters = {
  token: (state: StateAppModule) => state.token,
  userInfo: (state: StateAppModule) => state.userInfo,
  menuList: (state: StateAppModule) => state.menuList
}

const mutations = {
  increment(state: StateAppModule, clearFlag: boolean = false) {
    if (!clearFlag) {
      state.requestCount.count++
      state.requestCount.time = Date.now()
    } else {
      state.requestCount.count = 0
      state.requestCount.time = 0
    }
  },
  // 设置token
  SET_TOKEN: (state: StateAppModule, token: string) => {
    state.token = token
  },
  SET_REFRESHTOKEN: (state: StateAppModule, refreshToken: string) => {
    state.refreshToken = refreshToken
  },
  // 设置用户信息
  SET_USERINFO: (state: StateAppModule, userInfo: any) => {
    state.userInfo = userInfo
  },
  logouts() {
    router.push({
      path: '/login'
    })
  }
}

const actions = {
  /**
   * 登录action
   * @param param0
   * @param params
   * @returns
   */
  login({ dispatch, commit }: ActionContext<StateAppModule, RootStateTypes>, params: any) {
    return new Promise((resolve, reject) => {
      login(params)
        .then(async (res) => {
          const { data } = res
          commit('SET_TOKEN', data.accessToken)
          commit('SET_REFRESHTOKEN', data.keepLoginToken)
          // commit('SET_USERINFO', data)
          // const routeMenuList = Utils.arrayToTree(data.menus || [], 0)
          // if (routeMenuList.length > 0) {
          //   dispatch('routesList/setRoutesList', (routeMenuList as any)[0].children, { root: true })
          // }
          setSession('token', data.accessToken)
          setSession('refreshToken', data.keepLoginToken)
          resolve(data)
        })
        .catch((err) => {
          reject(err)
        })
    })
  },
  /**
   * 退出action
   * @param param0
   * @param params
   */
  logout({ dispatch, commit }: ActionContext<StateAppModule, RootStateTypes>) {
    commit('SET_TOKEN', '')
    commit('SET_REFRESHTOKEN', '')
    commit('SET_USERINFO', null)
    // dispatch('routesList/setRoutesList', [], { root: true })
    commit('increment', true)
    clearSession()
    commit('logouts')
  },
  /**
   * 过期刷新action
   * @param param0
   * @returns
   */
  refreshToken({ dispatch, commit }: ActionContext<StateAppModule, RootStateTypes>) {
    return new Promise((resolve, reject) => {
      let params = {
        refreshToken: getSession('refreshToken')
      }

      refreshLogin(params)
        .then((res: any) => {
          console.log(res, 'res')

          if (res.code === 'success' || res.code === 1) {
            commit('SET_TOKEN', res.data)
            setSession('token', res.data)
            resolve(res.data)
          }
        })
        .catch((err) => {
          dispatch('logout')
        })
    })
  }
}

type stateKey = typeof state
export type AppState = ModuleState<stateKey>
type gettersKey = typeof getters
export type AppGetters = ModuleGetters<gettersKey>
type mutationKey = typeof mutations
export type AppMutations = ModuleMutations<mutationKey>
type actionKey = typeof actions
export type AppActions = ModuleActions<actionKey>

const app: Module<StateAppModule, RootStateTypes> = {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}

export default app
